﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;

using System.Net.Mail;
using System.Net;
using System.Text;
using System.Collections.Generic;

using System.Data.Common;

using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;

using System.Diagnostics;
using System.IO;

using Eacademy.Domain.Models;
using Eacademy.Library.Membership;

/// <summary>
/// Summary description for Email
/// </summary>
///
namespace Eacademy.Library.Helpers
{
    public class EmailHelper
    {
        public EmailHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private static CustomMembershipProvider Provider
        {
            get
            {
                return (CustomMembershipProvider)System.Web.Security.Membership.Provider;
            }
        }

        protected static void SendEmailInAsyncMode(string fromEmailID, string emailTo, string body, string subject)
        {
            try
            {
                //string emailTo = "aivan@example.com";
                //string fromEmailID = "aivan@example.com";               

                // create email message object
                MailMessage message = new MailMessage();

                // set from address
                message.From = new MailAddress(AppSettings.ServerEmailAddress, "Bilmoko.com");

                // set to address
                message.To.Add(new MailAddress(emailTo, emailTo));

                // set email message content
                message.Body = body;

                // set email message heading
                message.Subject = subject;
                message.IsBodyHtml = true;

                //create a smtp client object
                SmtpClient client = new SmtpClient("mail.example.com");
                client.Credentials = new NetworkCredential("noreply@example.com", "passwords");
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.OnFailure;

                string userMessage = "test";

                client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                client.SendAsync(message, userMessage);
            }

            catch (Exception ex)
            {

                throw ex;
            }

        }

        static void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                Console.WriteLine("The message [{0}] was canceled", e.UserState.ToString());
            }

            if (e.Error != null)
            {
                StringBuilder errorMsg = new StringBuilder();
                errorMsg.Append(string.Format("An error occured sending message [{0}], {1}", e.UserState.ToString(), e.Error.Message));

                if (e.Error.InnerException != null)
                {
                    errorMsg.Append(Environment.NewLine + "Inner exception message: " + e.Error.InnerException.Message);
                    Console.WriteLine(errorMsg);
                }
                else
                {
                    Console.WriteLine("Message [{0} sent].", e.UserState.ToString());
                }
            }
        }

        public void GetResultsOnCallback(IAsyncResult ar)
        {
            SendEmailDelegate del = (SendEmailDelegate)
             ((AsyncResult)ar).AsyncDelegate;
            try
            {
                string result;
                result = del.EndInvoke(ar);
                Debug.WriteLine("\nOn CallBack: result is " + result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\nOn CallBack, problem occurred: " + ex.Message);
            }
        }

        public delegate string SendEmailDelegate(string name, string emailAddress);

        public string strBody = String.Empty;

        //public static void SendRegistrationEmailVerification(bool resend, string emailTo, string verificationCode, string returnUrl)
        //{

        //    string fromEmailID = AppSettings.ServerEmailAddress;

        //    StringBuilder strBody = new StringBuilder();

        //    UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);

        //    string confirmationUrl = url.AbsoluteAction("Verify", new { Controller = "Account", Code = verificationCode });

        //    strBody.Append("Dear User,<br/><br/>");

        //    strBody.Append("Welcome to Bilmoko.com Events!<br/>");
        //    strBody.Append("You have taken your first step in creating your Bilmoko Events account.  Please take time verifying your email address by clicking the link below.<br/>");

        //    strBody.AppendFormat("<br/><br/><a href='{0}'>{1}</a><br/><br/><br/>", confirmationUrl, confirmationUrl);

        //    strBody.Append("If you did not register for this account, just ignore this message, it will expire within 24 hours.<br/><br/><br/>");

        //    strBody.Append("If you need any further assistance, please ask us by email (support@bilmoko.com).<br/><br/>");
        //    strBody.Append("Sincerely, <br/><br/>");
        //    strBody.Append("The Bilmoko Team");
        //    string subject = "Bilmoko Events Confirm Registration";

        //    SendEmailInAsyncMode(fromEmailID, emailTo, strBody.ToString(), subject);

        //    if (resend == false)
        //    {
        //        strBody = new StringBuilder();
        //        strBody.Append("A new user has registered to Bilmoko Events! <br/><br/>");

        //        subject = "Bilmoko Events Registration";
        //        emailTo = "aivan@example.com";
        //        SendEmailInAsyncMode(fromEmailID, emailTo, strBody.ToString(), subject);

        //    }
        //}

        //public static void SendForgotPasswordEmail(User userInfo,Profile profile,HttpContextBase context,Boolean secondaryEmail)
        //{

        //    string fromEmailID = AppSettings.ServerEmailAddress;
        //    string emailTo = String.Empty;

        //    if (secondaryEmail)
        //    {
        //        emailTo = userInfo.UserPrimaryEmail;
        //    }
        //    else
        //    {
        //        emailTo = userInfo.UserAlternateEmail;
        //    }

        //    String name = String.Empty;
        //    switch (userInfo.UserTypeId)
        //    {
        //        case UserTypes.Member:
        //            name = profile.Firstname + " " + profile.Lastname;
        //            break;
        //        case UserTypes.Organizer:
        //            name = profile.CompanyName;
        //            break;
        //    }

        //    StringBuilder strBody = new StringBuilder();

        //    strBody.Append("<span style=\"font-family: verdana; color: #666666; font-size: 12px;\">");
        //    strBody.AppendFormat("Dear {0},<br/><br/>", name);
        //    strBody.Append("You have recently requested to reset your password. Click this link below to reset your password.");

        //    string url = String.Format("{0}/account/resetpassword?key={1}&user={2}",UrlHelperExtensions.SiteRoot(context), userInfo.UserPasswordKey, userInfo.UserPrimaryEmail);
        //    strBody.AppendFormat("<br/><br/><br/><a href='{0}'>{1}</a><br/><br/><br/>", url, url);

        //    strBody.Append("If clicking this link does not work, copy and paste the link into your web browser.<br/>");
        //    strBody.Append("If you did not request for this, just ignore this message, it will expire within 24 hours.<br/><br/><br/>");

        //    strBody.Append("Sincerely, <br/><br/>");
        //    strBody.Append("The SpeedyCourse Team</span>");

        //    strBody.Append("</span>");
        //    string subject = "Forgot Password";
        //    //email.SendEmailAsync(subject, emailTo);

        //    SendEmailInAsyncMode(fromEmailID, emailTo, strBody.ToString(), subject);

        //    emailTo = "aivan@example.com";
        //    SendEmailInAsyncMode(fromEmailID, emailTo, strBody.ToString(), subject);

        //}

        //public static void SendEventInformationEmailToFriend(Event events, string emailaddress,HttpContextBase context, string message = null)
        //{

        //    string fromEmailID = AppSettings.ServerEmailAddress;
        //    string emailTo = emailaddress;
        //    StringBuilder strBody = new StringBuilder();

        //    //Implement name
        //    String name = String.Empty;
        //    switch (Provider.User.UserTypeId)
        //    {
        //        case UserTypes.Member:
        //            name = Provider.Profile.Firstname + " " + Provider.Profile.Lastname;
        //            break;
        //        case UserTypes.Organizer:
        //            name = Provider.Profile.CompanyName;
        //            break;
        //    }

        //    string subject = string.Format("{0} wants to share an event with you.", name);


        //    if (!String.IsNullOrEmpty(emailaddress))
        //    {

        //        strBody = new StringBuilder();

        //        strBody.AppendFormat("Dear {0},<br/><br/>", emailaddress);
        //        strBody.AppendFormat("Your friend {0} , thinks you might be interested in this event. <br/><br/>", name);
        //        strBody.AppendFormat("Event Title: {0} <br/>", events.EventTitle);

        //        if (String.IsNullOrEmpty(message) == false)
        //        {
        //            strBody.AppendFormat("Message: {0} <br/>", message);
        //        }

        //        strBody.Append("<br/>For more details, please click on the URL below:");
        //        string url = String.Format("{0}/events/{1}/{2}", UrlHelperExtensions.SiteRoot(context), events.EventId, events.EventTitle.GenerateSlug());
                
        //        strBody.AppendFormat("<br/><br/><a href='{0}'>{1}</a><br/><br/><br/>", url, url);

        //        strBody.Append("Thank you.<br/><br/><br/>");
        //        strBody.Append("Sincerely, <br/><br/>");
        //        strBody.Append("The SpeedyCourse Team");

        //        SendEmailInAsyncMode(fromEmailID, emailaddress, strBody.ToString(), subject);
        //    }
        //}

        //public static void SendInquiryNotificationEmail(Event events, User user, Profile profile,InquiryViewModel inquiryViewModel)
        //{

        //    string fromEmailID = AppSettings.ServerEmailAddress;
        //    string emailTo = user.UserPrimaryEmail;

        //    StringBuilder strBody = new StringBuilder();
        //    String name = String.Empty;
        //    switch (user.UserTypeId)
        //    {
        //        case UserTypes.Member:
        //            name = profile.Firstname + " " + profile.Lastname;
        //            break;
        //        case UserTypes.Organizer:
        //            name = profile.CompanyName;
        //            break;
        //    }

        //    strBody.AppendFormat("Dear {0},<br/><br/>", name);
        //    strBody.AppendFormat("A user inquires about \"{0}\".<br/>", events.EventTitle);
        //    strBody.Append("Below are the details of the inquiry:<br/><br/>");
        //    strBody.AppendFormat("Sender's Name: {0}<br/>", inquiryViewModel.Name);
        //    strBody.AppendFormat("Time and Date of Inquiry: {0}<br/><br/>", DateTime.Now.ToShortDateString());

        //    strBody.Append("Please log in to Bilmoko.com to view for the details of this inquiry.<br/><br/>");

        //    strBody.Append("Sincerely, <br/><br/>");
        //    strBody.Append("The Bilmoko Team");
        //    string subject = events.EventTitle;

        //    SendEmailInAsyncMode(fromEmailID, emailTo, strBody.ToString(), subject);

        //    emailTo = "aivan@example.com";
        //    SendEmailInAsyncMode(fromEmailID, emailTo, strBody.ToString(), subject);

        //}
    }
}
